﻿using yao.Common;
using yao.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Titan;

namespace yao.website.Controllers
{
    /// <summary>
    /// 登录
    /// </summary>
    public class LoginController : BaseController
    {
        public ActionResult Index()
        {
            Employee employee = new Employee();
            HttpCookie cookieLoginNo = Request.Cookies["l"];
            if (cookieLoginNo != null) employee.LoginNo = cookieLoginNo.Value;

            //string s = "123456";
            //string s2=Encryption.GetMD5HashHex(s);
            //string s = Encryption.Encrypt("18858281757", "test");

            return View(employee);
        }

        [HttpPost]
        public ActionResult Index(Employee employee)
        {
            //获取请求数据
            string loginNo = employee.LoginNo;
            string passwordMD5 = Encryption.GetMD5HashHex(employee.Password.ToLower());
            employee.Password = "";
            string validateCode = (Request.Form["ValidateCode"] + "").ToLower();
            
            //判断验证码
            if (ApplicationType == ApplicationTypeEnum.Web && (string.IsNullOrWhiteSpace(validateCode) || Session["ValidateCode"] as string != validateCode))
            {
                AddPageError("验证码错误");
                return View(employee);
            }

            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(Employee);
                q.Selects.Add(Employee_.IsActive);//employee是否禁用 
                q.Selects.Add(Employee_.EmployeeId);
                q.Selects.Add(Employee_.Password);
                q.Selects.Add(Employee_.EmployeeName);
                q.Selects.Add(Employee_.CompanyId);
                q.Selects.Add(Employee_.Company.IsActive);//公司是否禁用
                q.Selects.Add(Employee_.Company.CompanyCode);
                q.Selects.Add(Employee_.Company.CompanyName);
                q.Selects.Add(Employee_.Company.AreaId);
                q.Wheres.Add(Employee_.LoginNo.TEqual(loginNo));
                Employees employees = new Employees();
                cn.SelectCollection(employees.Items, q);
                if (employees.Items.Count <= 0)
                {
                    AddPageError("用户名或密码错误，请重试");
                    return View(employee);
                }
                Employee dbEmployee = employees.Items[0];
                if (dbEmployee.Password != passwordMD5)
                {
                    AddPageError("用户名或密码错误，请重试");
                    return View(employee);
                }
                if (!dbEmployee.IsActive )
                {
                    AddPageError("用户已被禁用，请与贵公司系统管理员联系");
                    return View(employee);
                }
                if (!dbEmployee.Company.IsActive)
                {
                    AddPageError("公司账户已停用，请尽快与我们联系");
                    return View(employee);
                }
                //此时已经正确
                Session.Remove("ValidateCode");
                CurrentEmployee currentEmployee = new CurrentEmployee();
                currentEmployee.EmployeeId = dbEmployee.EmployeeId;
                currentEmployee.EmployeeName = dbEmployee.EmployeeName;
                currentEmployee.LoginNo = loginNo;
                currentEmployee.CompanyId = dbEmployee.CompanyId;
                currentEmployee.CompanyCode = dbEmployee.Company.CompanyCode;
                currentEmployee.CompanyName = dbEmployee.Company.CompanyName;
                currentEmployee.AreaId = dbEmployee.Company.AreaId;
                Response.SetCookie("_e", currentEmployee);
                Response.SetCookie("_k", (Response.Cookies["_e"].Value+CommonFun.GetIpAddress()).GetHashCode());
                Response.SetCookie("_o", (Response.Cookies["_e"].Value + Guid.NewGuid()).GetHashCode());
                SSOHelper.LoginRegister(currentEmployee.EmployeeId.ToString(),Response.Cookies["_o"].Value);

                if (ApplicationType == ApplicationTypeEnum.Web)
                {
                    string redirect = Request["u"] ?? "/";
                    return Redirect(redirect);
                }
                if (ApplicationType == ApplicationTypeEnum.App)
                {
                    return View(employee);
                }
                else
                {
                    return View();
                }
            }
        }

        public ActionResult ValidateCode()
        {
             
            ValidateCode validateCode = new ValidateCode();
            validateCode.Width = 100;
            validateCode.Height = 35;
            //生成验证码指定的长度
            string code = validateCode.GetRandomString(4);
            Session["ValidateCode"] = code.ToLower(); 
            //创建验证码的图片
            byte[] bytes = validateCode.CreateImage(code);
            //最后将验证码返回

            Response.AddHeader("cache-control", "no-store");
            return File(bytes, @"image/jpeg"); 

        }

        public ActionResult LoginOut()
        {
            Response.RemoveCookie("_e");
            Response.RemoveCookie("_k");
            Response.RemoveCookie("_o");
            return RedirectToAction("Index", "Home");
        }
    }
}
